package concurrent.application;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.util.concurrent.*;

/**
 * @program JavaBase
 * @description:
 * @author: zhanglu
 * @create: 2021-06-01 14:37:00
 */
@Slf4j
public class CountDownLatchDemo {

    @Test
    public void test01() throws InterruptedException {
        ExecutorService service = Executors.newFixedThreadPool(2);
        CountDownLatch countDownLatch = new CountDownLatch(2);
        service.submit(() -> {
            log.info("子任务执行完毕～");
            countDownLatch.countDown();
        });
        service.submit(() -> {
            log.info("子任务执行完毕～");
            countDownLatch.countDown();
        });
        countDownLatch.await();
        log.info("ok～");
    }

    @Test
    public void test02() throws InterruptedException {
        Thread main = Thread.currentThread();
        ExecutorService service = Executors.newFixedThreadPool(3);
        CountDownLatch countDownLatch = new CountDownLatch(2);
        for (int i = 0; i < 2; i++) {
            service.submit(() -> {
                try {
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                log.info("子任务执行完毕～");
                countDownLatch.countDown();
            });
        }
        service.submit(() -> {
            try {
                TimeUnit.SECONDS.sleep(1);
                main.interrupt();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        countDownLatch.await();
        log.info("ok～");
    }

    @Test
    public void test03() throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(2);
        Thread t1 = new Thread(() -> {
            log.info("子任务执行完毕～");
            countDownLatch.countDown();
        });
        Thread t2 = new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
                log.info("子任务执行完毕～");
                countDownLatch.countDown();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        t1.start();
        t2.start();
        t2.interrupt();
        countDownLatch.await();
        log.info("ok～");
    }


}
